﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Media;
using System.ServiceModel;
using System.Windows.Threading;

namespace Client
{
    [ServiceContract]
    public interface IChat
    {
        [OperationContract]
        string ReverseString(string str);

        [OperationContract]
        bool Join(string nickname);

        [OperationContract]
        void Disconnect(string nickname);

        [OperationContract]
        void ReceiveMessage(string nickname, string message);

        [OperationContract]
        Tuple<int, List<Tuple<string, string>>> GetNewMessages(string nickname, int idLastMessage);

        [OperationContract]
        List<string> Users();

        [OperationContract]
        bool Live();
    }

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        private ChannelFactory<IChat> _factory;
        private IChat _proxy;
        private bool _proxyFlag = false;

        private int _lastMessageId = -1;
        private string _nick;

        private readonly ObservableCollection<string> _messages = new ObservableCollection<string>();
        private readonly ObservableCollection<string> _users = new ObservableCollection<string>();

        private readonly DispatcherTimer _work;

        public ObservableCollection<string> MessageList
        {
            get { return _messages; }
        }

        public ObservableCollection<string> UsersList
        {
            get { return _users; }
        }

        public MainWindow()
        {
            _proxy = null;
            InitializeComponent();

            Users.DataContext = this;
            Messages.DataContext = this;

            _work = new DispatcherTimer {Interval = TimeSpan.FromMilliseconds(250)};
            _work.Tick += WorkTick;
        }

        void WorkTick(object sender, EventArgs e)
        {
            lock (_proxy)
            {
                try
                {
                    UpdateUsers();
                    UpdateMessages();
                }
                catch (Exception ex)
                {
                    _work.Stop();
                    _proxyFlag = false;
                    _proxy = null;
                    _factory = null;

                    ConnectIndicator.Fill = new SolidColorBrush(Colors.Red);
                    JoinIndicator.Fill = new SolidColorBrush(Colors.Red);

                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void ButtonClick(object sender, RoutedEventArgs e)
        {
            try
            {
                _work.Stop();

                _factory = new ChannelFactory<IChat>(
                    new NetTcpBinding(SecurityMode.None), new EndpointAddress(string.Format("net.tcp://{0}/Chat", ServerIP.Text)));

                _messages.Clear();
                _users.Clear();
                if (_proxyFlag == true)
                {
                    _proxy.Disconnect(_nick);
                    _proxyFlag = false;
                    ConnectIndicator.Fill = new SolidColorBrush(Colors.Red);
                    JoinIndicator.Fill = new SolidColorBrush(Colors.Red);
                }

                _proxy = _factory.CreateChannel();
                _proxyFlag = true;

                ConnectIndicator.Fill = new SolidColorBrush(Colors.Green);
            }
            catch (Exception ex)
            {
                JoinIndicator.Fill = new SolidColorBrush(Colors.Red);
                _proxyFlag = false;
                MessageBox.Show(ex.Message);
            }
        }

        private void ButtonClick1(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_proxy.Join(Nickname.Text))
                {
                    JoinIndicator.Fill = new SolidColorBrush(Colors.Green);

                    _nick = Nickname.Text;

                    _work.Start();
                }
            }
            catch (Exception ex)
            {
                JoinIndicator.Fill = new SolidColorBrush(Colors.Red);
                _proxyFlag = false;
                MessageBox.Show(ex.Message);
            }
        }

        private void UpdateUsers()
        {
            if (_proxy == null) return;
            var tmp = _proxy.Users();

            foreach (var u in tmp.Where(u => !UsersList.Contains(u)))
                UsersList.Add(u);
        }

        private void UpdateMessages()
        {
            if (_proxyFlag == false) return;

            var tmp = _proxy.GetNewMessages(_nick, _lastMessageId);
            _lastMessageId = tmp.Item1;

            foreach (var msg in tmp.Item2)
                MessageList.Add(msg.Item1 + ": " + msg.Item2);
        }

        protected override void OnClosed(EventArgs e)
        {
            try
            {
                if (_proxyFlag == true)
                {
                    _proxy.Disconnect(_nick);
                    _proxyFlag = false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void ButtonClick2(object sender, RoutedEventArgs e)
        {
            var txt = SendingMessage.Text;
            SendingMessage.Text = "";

            if (_proxyFlag == false) return;

            _proxy.ReceiveMessage(_nick, txt);
        }
    }
}
